import {getAuthorization} from '@/utils/auth';
import * as env from '@/env.js';

let theartbeat = null;

let wsUrl = env.default.baseWs+'/api/supervise/endpointMsg?access_token=';;

// webSocket.js
// 1.创建一个 WebSocket连接
export function connectSocket() {
	let token = getAuthorization();
	if(token!=null){
		uni.connectSocket({
		  // 后端提供的地址，http用ws，https用wss
			url:wsUrl+token
		});
	}else{
		console.log('###token is empty!');
	}
  
}

export function reconnect(){
	uni.closeSocket({
		complete:()=>{
			connectSocket();
			initSocket();
		}
	});
}


export function initSocket(){
	uni.onSocketClose(res=> {
	  console.log('WebSocket 已关闭！');
	});
	
	uni.onSocketMessage(res=> {
	  let data = JSON.parse(res.data);
	  if(data.msgType==='Jar'){
		//console.log('收到服务器内容：',data);
		uni.$emit('update:monitor_jar',data.data);
	  }else if(data.msgType==='JobAll'){
		console.log('3333333,',data);
	  }else if(data.msgType==='Job'){
		
	  }
	});
	
	uni.onSocketError(res=> {
	  console.log('WebSocket连接打开失败，请检查！');
	});
	
	startHeatbeat();
}

export function send(msg){
	uni.sendSocketMessage({
	  data: msg,
	  fail:err=>{
		  let msgBody = JSON.parse(msg);
		  console.log('eeeerrrr,',msgBody);
		  if(msgBody.type==='HeatBeat'){
			  console.log('eeeerrrr,',err);
			  connectSocket();
		  }
		  
	  }
	});
}


//开启心跳检测
function startHeatbeat(){
	theartbeat = setInterval(()=>{
	   let data = {type:"HeatBeat"};
	   send(JSON.stringify(data));
	}, 2000);
}

 